package com.destroyer.core.feign.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class FeignConfig implements RequestInterceptor {
    /**
     * Token名称
     */
    @Value("${access-token-name}")
    private String accessTokenName;

    /**
     * 参数携带Token名
     */
    private final static String paramTokenName = "token";


    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获取request
        HttpServletRequest request = attributes.getRequest();
        // 获取Header中的tokenValue
        String token = request.getHeader(accessTokenName);
        //第一次为空，则看参数中是否带
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(paramTokenName);
        }
        // 注入Feign的请求中,这里header中token的key需要和被调用方一致
        requestTemplate.header(accessTokenName, token);
    }
}